<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>宠物救助聊天</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100 min-h-screen">
<div class="container mx-auto px-4 py-8 max-w-2xl">
    <h1 class="text-2xl font-bold text-center mb-6 text-gray-800">宠物救助聊天系统</h1>

    <!-- 登录区域 -->
    <div id="loginArea" class="bg-white rounded-lg shadow-md p-4 mb-4">
        <h2 class="text-lg font-semibold mb-3">请先登录</h2>
        <div class="flex gap-2">
            <input type="number" id="currentUserId" placeholder="请输入您的用户ID"
                   class="flex-1 px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            <button id="loginButton"
                    class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md transition-colors">
                <i class="fa fa-sign-in mr-1"></i>登录
            </button>
        </div>
    </div>

    <!-- 聊天区域（初始隐藏） -->
    <div id="chatArea" class="hidden">
        <!-- 连接状态 -->
        <div id="status" class="bg-yellow-100 text-yellow-800 p-3 rounded mb-4 flex items-center">
            <i class="fa fa-circle-o-notch fa-spin mr-2"></i>
            <span>正在连接...</span>
        </div>

        <!-- 消息列表 -->
        <div id="messageList" class="bg-white rounded-lg shadow-md p-4 h-80 overflow-y-auto mb-4"></div>

        <!-- 输入区域 -->
        <div class="flex gap-2">
            <input type="number" id="targetUserId" placeholder="接收用户ID"
                   class="flex-1 px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            <input type="text" id="messageInput" placeholder="输入消息..."
                   class="flex-3 px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            <button id="sendButton"
                    class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md transition-colors">
                <i class="fa fa-paper-plane mr-1"></i>发送
            </button>
        </div>
    </div>
</div>

<script>
    // 当前用户ID - 通过登录获取
    let currentUserId = null;

    // WebSocket连接
    let websocket = null;

    // DOM元素
    const loginArea = document.getElementById('loginArea');
    const chatArea = document.getElementById('chatArea');
    const statusElement = document.getElementById('status');
    const messageList = document.getElementById('messageList');
    const messageInput = document.getElementById('messageInput');
    const targetUserId = document.getElementById('targetUserId');
    const sendButton = document.getElementById('sendButton');
    const loginButton = document.getElementById('loginButton');
    const currentUserIdInput = document.getElementById('currentUserId');

    // 登录功能
    function login() {
        const userId = currentUserIdInput.value.trim();

        if (!userId) {
            alert('请输入用户ID');
            return;
        }

        currentUserId = parseInt(userId);

        // 隐藏登录区域，显示聊天区域
        loginArea.classList.add('hidden');
        chatArea.classList.remove('hidden');

        // 初始化WebSocket连接
        initWebSocket();
    }

    // 初始化WebSocket连接
    function initWebSocket() {
        // 连接WebSocket服务器
        const wsUri = `ws://localhost:8080/websocket/${currentUserId}`;
        websocket = new WebSocket(wsUri);

        // 连接成功
        websocket.onopen = function() {
            statusElement.className = 'bg-green-100 text-green-800 p-3 rounded mb-4 flex items-center';
            statusElement.innerHTML = '<i class="fa fa-check-circle mr-2"></i><span>已连接</span>';
            addMessage('系统', `连接成功，您的用户ID是 ${currentUserId}，可以开始聊天了`);
        };

        // 接收消息
        websocket.onmessage = function(event) {
            const message = event.data;
            // 解析消息格式: 接收ID:消息内容
            const colonIndex = message.indexOf(':');
            if (colonIndex > 0) {
                const senderId = message.substring(0, colonIndex);
                const content = message.substring(colonIndex + 1);
                addMessage(`用户${senderId}`, content);
            } else {
                // 系统消息
                addMessage('系统', message);
            }
        };

        // 连接关闭
        websocket.onclose = function() {
            statusElement.className = 'bg-red-100 text-red-800 p-3 rounded mb-4 flex items-center';
            statusElement.innerHTML = '<i class="fa fa-times-circle mr-2"></i><span>连接已关闭</span>';
            addMessage('系统', '连接已关闭，正在尝试重连...');

            // 尝试重连
            setTimeout(initWebSocket, 3000);
        };

        // 连接错误
        websocket.onerror = function(error) {
            statusElement.className = 'bg-red-100 text-red-800 p-3 rounded mb-4 flex items-center';
            statusElement.innerHTML = '<i class="fa fa-exclamation-triangle mr-2"></i><span>连接错误</span>';
            addMessage('系统', '连接发生错误: ' + error);
        };
    }

    // 添加消息到消息列表
    function addMessage(sender, content) {
        const messageElement = document.createElement('div');
        messageElement.className = 'mb-3 p-2 rounded bg-gray-50 border-l-4 border-blue-500';

        const senderElement = document.createElement('div');
        senderElement.className = 'text-sm font-semibold text-gray-700';
        senderElement.textContent = sender;

        const contentElement = document.createElement('div');
        contentElement.className = 'text-gray-800';
        contentElement.textContent = content;

        const timeElement = document.createElement('div');
        timeElement.className = 'text-xs text-gray-500 mt-1';
        timeElement.textContent = new Date().toLocaleTimeString();

        messageElement.appendChild(senderElement);
        messageElement.appendChild(contentElement);
        messageElement.appendChild(timeElement);

        messageList.appendChild(messageElement);
        // 滚动到底部
        messageList.scrollTop = messageList.scrollHeight;
    }

    // 发送消息
    function sendMessage() {
        const targetId = targetUserId.value.trim();
        const message = messageInput.value.trim();

        if (!targetId || !message) {
            alert('请输入接收用户ID和消息内容');
            return;
        }

        if (websocket && websocket.readyState === WebSocket.OPEN) {
            // 按照后端要求的格式发送: 接收ID:消息内容
            const sendData = `${targetId}:${message}`;
            websocket.send(sendData);
            addMessage('我', message);
            messageInput.value = '';
        } else {
            addMessage('系统', '连接未建立，无法发送消息');
        }
    }

    // 事件监听
    loginButton.addEventListener('click', login);
    sendButton.addEventListener('click', sendMessage);

    // 按Enter登录或发送消息
    currentUserIdInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            login();
        }
    });

    messageInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });
</script>
</body>
</html>